package com.jkkc.lib.base.util.usb

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.jkkc.lib.base.extend.ACTION_USB_PERMISSION
import com.jkkc.lib.base.extend.BOOLEAN_FALSE

/**
 * Author:LiXian
 * <p>
 * Desc:USB状态广播
 * Version:1.0
 * date 2023/2/13 10:20
 */
//获取USB设备ACTION
class UsbStateReceiver(var iUsbChangedListener: IUsbChangedListener) : BroadcastReceiver() {

    @Synchronized
    override fun onReceive(context: Context, intent: Intent) {
        val usbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
        val isGranted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, BOOLEAN_FALSE)
        when(intent.action) {
            UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                iUsbChangedListener.insertUsb(isGranted, usbDevice)
            }

            ACTION_USB_PERMISSION -> {
                iUsbChangedListener.applyPermissionResult(isGranted, usbDevice)
            }

            UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                iUsbChangedListener.removeUsb(usbDevice)
            }
        }
    }
}